package com.squid.cloud.fuel.purchase.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.squid.cloud.common.component.BusinessProperties;
import com.squid.cloud.common.component.generaterno.GeneraterNo;
import com.squid.cloud.common.enums.CommonEnum;
import com.squid.cloud.common.enums.DepositOrderStatusEnum;
import com.squid.cloud.common.enums.ErrorCodeEnum;
import com.squid.cloud.common.enums.OilNoEnum;
import com.squid.cloud.common.exception.BusinessException;
import com.squid.cloud.common.util.CollectionUtil;
import com.squid.cloud.common.util.DateUtil;
import com.squid.cloud.common.util.StringUtils;
import com.squid.cloud.model.entity.CustomerAccountEntity;
import com.squid.cloud.model.entity.CustomerHeadEntity;
import com.squid.cloud.model.entity.DepositOrderEntity;

import lombok.extern.slf4j.Slf4j;

@Service("depositOrderService")
@Slf4j
public class DepositOrderService extends BaseService<DepositOrderEntity, String> {
	@Autowired
	private GeneraterNo generater;

	@Autowired
	BusinessProperties businessProperties;

	@Autowired
	private DepositOrderRepository depositOrderRepository;

	@Autowired
	private DepositRefundOrderRepository depositRefundOrderRepository;

	@Autowired
	private CustomerAccountService customerAccountService;

	@Autowired
	private PropertyService propertyService;

	@Autowired
	private CustomerHeadService customerHeadService;

	@Autowired
	private CustomerSourceService customerSourceService;

	@Autowired
	private DepositRefundOrderService depositRefundOrderService;

	@Autowired
	private SystemMessgeSender systemMessgeSender;

	@Autowired
	private CardRechargeService cardRechargeService;

	@Autowired
	private TradeUserCardService tradeUserCardService;
	@Autowired
	IndustryService industryService;
	@Autowired
	CustomerWhiteService customerWhiteService;
	private static final String WHITE_MOBILE_RECHARGE_LIMIT = "white_mobile_recharge_limit";
	/**
	 * 创建订单
	 *
	 * @param order
	 * @return
	 */
	@Transactional
	public DepositOrderEntity create(DepositOrderEntity order) {
		// 创建本地订单
		CustomerHeadBizBean customer = customerHeadService.queryEntityById(order.getCustomerId());
		if (customer == null) {
			throw new BusinessException("1011", "用户不存在");
		}
		CustomerAccountEntity account = customerAccountService.queryAccountByOilNoWithCreate(order.getCustomerId(), OilNo.code2OilNo(order.getOilNo()));
		// CustomerAccountEntity account =
		// customerAccountService.queryBalance(order.getCustomerId());
		if (account == null) {
			throw new BusinessException(ErrorCodeEnum.USERNOTEXISTS);
		}
		if (account.getStatus().equals(CommonEnum.Y.code())) {
			throw new BusinessException(ErrorCodeEnum.USERFORBIDDEN);
		}
		checkChargeAmount(order,customer);
		order.setOrderNo(generater.newOrderNo());
		if (OilNoEnum.WX.getCode().equals(order.getOilNo())) {
			order.setSource(Constants.WECHAT);
			if (StringUtils.isEmpty(order.getCardNo())) {
				throw new BusinessException("1011", "油卡卡号为空");
			}
			TradeUserCardEntity card = tradeUserCardService.findBindInfoByCardNo(order.getCardNo());
			if (card == null || !order.getCustomerId().equals(card.getCustomerId()) || !"Y".equals(card.getStatus())) {
				throw new BusinessException("1011", "油卡卡号错误");
			}
			CacheManage.getInstance().setAttributeObj("deposit_card:" + customer.getEntityId() + "_" + order.getOrderNo(), order.getCardNo());
		} else {
			order.setSource(Constants.APP);
		}
		order.setAccountId(account.getAccountId());
		order.setDepositDate(new Date());
		order.setStatus(DepositOrderStatusEnum.WAIT_PAY.getCode());
		order.setInvoicedAmount(0L);
		order.setPhoneNo(customer.getPhone());
		order.setNickname(customer.getNickName());
		return super.save(order);
	}

	private void checkChargeAmount(DepositOrderEntity order, CustomerHeadBizBean customer) {
		checkWihteChargeAmount(order,customer);
	}

	/**
	 * 获取预支付信息
	 *
	 * @param order
	 * @return
	 */
	@Transactional
	public String prepay(DepositOrderDto order) {
		DepositOrderEntity db = depositOrderRepository.findByOrderNo(order.getOrderNo());
		if (db == null) {
			throw new BusinessException(ErrorCodeEnum.ORDERNOTEXISTS);
		}
		if (!db.getStatus().equals(DepositOrderStatusEnum.WAIT_PAY.getCode())) {
			throw new BusinessException(ErrorCodeEnum.ORDERSTATUSERROR);
		}
		String prepayNo = generater.newNo(NoType.PAYMENT);
		// 更新充值订单
		db.setPrepayNo(prepayNo);
		// 支付方式
		db.setPayMode(order.getPayMode());
		// 支付来源
		db.setSource(order.getSource());
		super.update(db);

		// 调用支付接口创建支付订单
		CustomerAccountEntity account = customerAccountService.queryAccountByOilNo(db.getCustomerId(), OilNo.code2OilNo(db.getOilNo()));
		invokeSettleCreateDespositeOrder(db, prepayNo, account);

		// 调用支付接口获取预支付信息
		PaymentPayRequest payRequest = null;
		if (order.getPayMode().equals(PayMode.WECHATH5.getCode())) {
			payRequest = new PaymentPayRequest(PaymentServiceEnum.WECHAT_PUBLIC_PAY.service(), prepayNo, "/deposit/notify");
			payRequest.setOpenId(order.getOpenid());
		} else if (order.getPayMode().equals(PayMode.WECHATH5PAGE.getCode())) {
			payRequest = new PaymentPayRequest(PaymentServiceEnum.WECHAT_H5_PAY.service(), prepayNo, "/deposit/notify");
			payRequest.setReturnUrl(order.getReturnUrl());
			if (StringUtils.isEmpty(order.getUserIp())) {
				log.error("缺少用户IP信息");
				throw new BusinessException(ErrorCodeEnum.USERIPNOTEXISTS);
			}
			payRequest.setUserIp(order.getUserIp());
			payRequest.setOpenId(order.getOpenid());
		} else if (order.getPayMode().equals(PayMode.ALIPAYH5.getCode())) {
			payRequest = new PaymentPayRequest(PaymentServiceEnum.ALI_H5_PAY.service(), prepayNo, "/deposit/notify");
			// 增加同步支付完成跳转页面配置
			payRequest.setReturnUrl(order.getReturnUrl());
			payRequest.setOpenId(order.getOpenid());
		} else if (order.getPayMode().equals(PayMode.WECHAT.getCode())) {
			payRequest = new PaymentPayRequest(PaymentServiceEnum.WX_APP_PAY.service(), prepayNo, "/deposit/notify");
		} else if (order.getPayMode().equals(PayMode.ALIPAY.getCode())) {
			payRequest = new PaymentPayRequest(PaymentServiceEnum.ALI_APP_PAY.service(), prepayNo, "/deposit/notify");
		}
		payRequest.setProductInfo("鱿鱼加油");
		payRequest.setSubject("鱿鱼加油");
		
		PaymentPayResponse payResponse = PaymentUtil.doPost(MapUtils.beanToStringMap(payRequest), PaymentPayResponse.class);
		if (!payResponse.isSuccess() || StringUtils.isBlank(payResponse.getPayInfoJson())) {
			throw new BusinessException(payResponse.getResultCode(), payResponse.getResultDetail());
		}
		if (payResponse.getResultCode().equals("60013")) {
			throw new BusinessException(ErrorCodeEnum.ORDERPAYEDERROR);
		}

		return payResponse.getPayInfoJson();
	}

	/**
	 * 调用清结算创建购油订单
	 * @param db	购油订单信息
	 * @param prepayNo	预支付号
	 * @param account	账户信息
	 */
	private void invokeSettleCreateDespositeOrder(DepositOrderEntity db, String prepayNo, CustomerAccountEntity account) {
		PaymentOrderRequest createOrderRequest = new PaymentOrderRequest(PaymentServiceEnum.ORDER_CREATE.service());
		createOrderRequest.setTradeName("鱿鱼加油");
		createOrderRequest.setSellerMerchUserId(account.getAccountId());
		createOrderRequest.setPayerMerchUserId(businessProperties.getPayment().getDefault_payer());
		
		if(db.getPayAmount() != null){
			// 实际用户需要支付金额
			createOrderRequest.setAmount(Money.cent(Long.parseLong(db.getPayAmount().toString())).toString());
			// 给用户赠送金额
			createOrderRequest.setDiscountAmount(Money.cent(db.getAmount() - db.getPayAmount()).toString());
			// 赠送钱从那个账户出
			createOrderRequest.setDiscountMerchUserId(businessProperties.getAccount().getCoupon_account_id());
		} else {
			createOrderRequest.setAmount(Money.cent(Long.parseLong(db.getAmount().toString())).toString());
		}
		createOrderRequest.setTradeTime(PaymentUtil.getDate(0));
		createOrderRequest.setCloseTime(PaymentUtil.getDate(5));
		createOrderRequest.setMerchOrderNo(prepayNo);
		createOrderRequest.setProfitType("AUTO");
		PaymentOrderResponse createOrderResponse = PaymentUtil.doPost(MapUtils.beanToStringMap(createOrderRequest), PaymentOrderResponse.class);
		if (!createOrderResponse.isSuccess()) {
			throw new BusinessException(ErrorCodeEnum.ORDERCREATEERROR);
		}
	}

	/**
	 * 获取购油金额限制
	 *
	 * @return
	 */
	public DepositRestrict getDepositRestrict() {
		String maxKey = "deposit_restrict_max";
		String minKey = "deposit_restrict_min";
		DepositRestrict restrict = new DepositRestrict();
		String max = PropertyCacheManage.getPropertyValueByKey(maxKey);
		String min = PropertyCacheManage.getPropertyValueByKey(minKey);
		if (StringUtils.isEmpty(max)) {
			PropertyEntity p = propertyService.getPropertyByKey(maxKey);
			if (p == null || StringUtils.isEmpty(p.getPropertyValue())) {
				restrict.setMaxAmount(1000000L);
			} else {
				// TODO 判断转换失败的情况
				restrict.setMaxAmount(Long.valueOf(p.getPropertyValue()));
			}
		} else {
			restrict.setMaxAmount(Long.valueOf(max));
		}
		if (StringUtils.isEmpty(min)) {
			PropertyEntity p = propertyService.getPropertyByKey(minKey);
			if (p == null || StringUtils.isEmpty(p.getPropertyValue())) {
				restrict.setMinAmount(100L);
			} else {
				// TODO 判断转换失败的情况
				restrict.setMinAmount(Long.valueOf(p.getPropertyValue()));
			}
		} else {
			restrict.setMinAmount(Long.valueOf(min));
		}
		return restrict;
	}

	@Transactional
	public void updateOrderByPrepayNoWhenNotify(DepositOrderEntity order) {
		DepositOrderEntity db = depositOrderRepository.findByPrepayNo(order.getPrepayNo());
		if (db == null) {
			log.error("未找到的prepayNo:" + order.getPrepayNo());
			throw new BusinessException(ErrorCodeEnum.ORDERNOTEXISTS);
		}
		if (db.getStatus().equals(DepositOrderStatusEnum.SUCCESS.getCode()) || db.getStatus().equals(DepositOrderStatusEnum.FAIL.getCode())) {
			return;
		}
		if (StringUtils.isNotEmpty(order.getPayMode())) {
			db.setPayMode(order.getPayMode());
		}
		if (StringUtils.isNotEmpty(order.getPayNo())) {
			db.setPayNo(order.getPayNo());
		}
		db.setStatus(order.getStatus());
		db.setFinishDate(new Date());
		super.update(db);
		if (Constants.WECHAT.equals(db.getSource())) {
			String cardNo = (String) CacheManage.getInstance().getAttributeObj("deposit_card:" + db.getCustomerId() + "_" + db.getOrderNo());
			if(StringUtils.isNotEmpty(cardNo)){
				CardRechargeEntity cardRecharge = new CardRechargeEntity();
				cardRecharge.setViceCardNo(cardNo);
				cardRecharge.setChannel(db.getPayMode());
				cardRecharge.setCustomerId(db.getCustomerId());
				cardRecharge.setDepositId(db.getEntityId());
				cardRecharge.setOrderNo(db.getOrderNo());
				cardRecharge.setPayAmount(db.getAmount().intValue());
				cardRecharge.setPayTime(db.getDepositDate());
				cardRecharge.setStatus(RechargeStatus.WAIT_RECHARGE.getCode());
				cardRecharge.setSource(RechargeSource.RECHARGE.getCode());
				cardRechargeService.saveEntity(cardRecharge);
			}
		}
		if(db.getPayAmount() != null){
			customerAccountService.updateBalanceAndInvoceAccount(db.getCustomerId(), db.getPayAmount(), OilNo.code2OilNo(db.getOilNo()));
		} else {
			customerAccountService.updateBalanceAndInvoceAccount(db.getCustomerId(), db.getAmount(), OilNo.code2OilNo(db.getOilNo()));
		}
		CacheManage.getInstance().removeAttribute("deposit_card:" + db.getCustomerId() + "_" + db.getOrderNo());
	}

	/**
	 * 获取可开票金额
	 *
	 * @param customerId
	 *            用户ID
	 * @return 可开票金额，单位：分
	 */
	public Long getUninvoicedAmount(String customerId) {
		List<DepositOrderEntity> orders = findUninvoicedOrder(customerId);
		if (CollectionUtil.isEmpty(orders)) {
			return 0L;
		}
		long total = 0;
		long invoiced = 0;
		for (DepositOrderEntity o : orders) {
			total += o.getAmount();
			invoiced += o.getInvoicedAmount();
		}
		return total - invoiced;
	}

	/**
	 * 获取可开票金额
	 *
	 * @param customerId
	 *            用户ID
	 * @param oilNo
	 *            油号
	 * @return 可开票金额，单位：分
	 */
	public Long getUninvoicedAmount(String customerId, String oilNo) {
		List<DepositOrderEntity> orders = findUninvoicedOrder(customerId, oilNo);
		if (CollectionUtil.isEmpty(orders)) {
			return 0L;
		}
		long total = 0;
		long invoiced = 0;
		for (DepositOrderEntity o : orders) {
			total += o.getAmount();
			invoiced += o.getInvoicedAmount();
		}
		return total - invoiced;
	}

	public DepositOrderEntity findByOrderNo(String orderNo) {
		DepositOrderEntity order = depositOrderRepository.findByOrderNo(orderNo);
		if (order == null) {
			throw new BusinessException("1011", "订单不存在");
		}
		if (order.getMarkDelete().equals(MARK_DELETE_YES)) {
			throw new BusinessException("1011", "订单已删除");
		}
		return order;
	}

	public DepositOrderEntity findByPrepayNo(String prepayNo) {
		DepositOrderEntity order = depositOrderRepository.findByPrepayNo(prepayNo);
		if (order == null) {
			throw new BusinessException("1011", "订单不存在");
		}
		if (order.getMarkDelete().equals(MARK_DELETE_YES)) {
			throw new BusinessException("1011", "订单已删除");
		}
		return order;
	}

	/**
	 * 退款
	 *
	 * @param order
	 */
	@Transactional
	public RefundOrderStatus refund(DepositOrderEntity order) {
		DepositOrderEntity db = depositOrderRepository.findOne(order.getId());
		if (db == null) {
			throw new BusinessException("1011", "订单不存在");
		}
		if (db.getMarkDelete().equals(MARK_DELETE_YES)) {
			throw new BusinessException("1011", "订单已删除");
		}
		if (db.getStatus().equals(DepositOrderStatusEnum.REFUND_SUCCESS.getCode())) {
			throw new BusinessException("1011", "订单已退款");
		}
		if (db.getStatus().equals(DepositOrderStatusEnum.WAIT_PAY.getCode())) {
			throw new BusinessException("1011", "待支付订单不能退款");
		}
		if (db.getStatus().equals(DepositOrderStatusEnum.FAIL.getCode())) {
			throw new BusinessException("1011", "未支付成功订单不能退款");
		}
		DepositRefundOrderEntity exitedRefund = depositRefundOrderRepository.findByDepositOrderNo(db.getOrderNo());
		if (exitedRefund != null && exitedRefund.getRefundStatus().equals(RefundOrderStatus.REFUND_SUCCESS)) {
			throw new BusinessException("1011", "订单已退款");
		}

		// 创建退款订单
		DepositRefundOrderEntity refund = depositRefundOrderService.create(db);

		// 调用清结算发起退款
		PaymentOrderQueryRequest refundRequest = new PaymentOrderQueryRequest(PaymentServiceEnum.ORDER_REFUND.service());
		refundRequest.setMerchOrderNo(refund.getRefundOrderNo());
		refundRequest.setOrigMerchOrdeNo(refund.getDepositOrderNo());
		PaymentRefundResponse refundResponse = PaymentUtil.doPost(MapUtils.beanToStringMap(refundRequest), PaymentRefundResponse.class);
		if (!refundResponse.isSuccess()) {
			// throw new
			// BusinessException(ExcCodeEnum.SYSTEM.code(),ExcCodeEnum.SYSTEM.message());
			throw new BusinessException("1011", ExcCodeEnum.SYSTEM.message());
		}
		if (!"REFUND".equals(refundResponse.getTradeStatus())) {
			depositRefundOrderService.updateWhenRefunded(refund.getRefundOrderNo(), RefundOrderStatus.REFUND_FAILED);
			return RefundOrderStatus.REFUND_FAILED;
		} else {
			// 修改退款订单状态
			depositRefundOrderService.updateWhenRefunded(refund.getRefundOrderNo(), RefundOrderStatus.REFUND_SUCCESS);
			// 修改充值订单状态
			db.setStatus(DepositOrderStatusEnum.REFUND_SUCCESS.getCode());
			super.update(db);

			// 退款成功给用户发送消息
			try {
				SystemMessgeSender.SystemMessage type = SystemMessgeSender.SystemMessage.DepositRefundSuccess;
				String userId = refund.getCustomerId();
				Map<String, String> map = new HashMap<>();
				map.put("orderNo", order.getOrderNo());
				map.put("refundOrderNo", refund.getRefundOrderNo());
				map.put("refundAmount", Money.cent(refund.getRefundAmount()).getAmount().toString());
				systemMessgeSender.send(type, userId, map);
			} catch (Exception e) {
				log.error("退款成功给用户发送消息失败", e);
			}

			return RefundOrderStatus.REFUND_SUCCESS;
		}
	}

	/**
	 * 获取充值（购油）说明
	 *
	 * @return
	 */
	public String getDepositDescription() {
		String key = "deposit_description";
		String description = PropertyCacheManage.getPropertyValueByKey(key);
		if (StringUtils.isEmpty(description)) {
			PropertyEntity p = propertyService.getPropertyByKey(key);
			if (p == null || StringUtils.isEmpty(p.getPropertyValue())) {
				description = "";
			} else {
				description = p.getPropertyValue();
			}
		}
		return description;
	}

	public DepositOrderEntity findByPayNo(String payNo) {
		DepositOrderEntity order = depositOrderRepository.findByPayNo(payNo);
		if (order == null) {
			throw new BusinessException("1011", "订单不存在");
		}
		if (order.getMarkDelete().equals(MARK_DELETE_YES)) {
			throw new BusinessException("1011", "订单已删除");
		}
		return order;
	}

	/**
	 * 删除待支付订单
	 *
	 * @param order
	 * @return
	 */
	@Transactional
	public DepositOrderEntity deleteWaitpayOrder(DepositOrderEntity order) {
		DepositOrderEntity db = depositOrderRepository.findByOrderNo(order.getOrderNo());
		if (db == null) {
			throw new BusinessException("1011", "订单不存在");
		}
		if (!db.getStatus().equals(DepositOrderStatusEnum.WAIT_PAY.getCode())) {
			throw new BusinessException("1011", "订单状态不正确");
		}
		db.setMarkDelete(MARK_DELETE_YES);
		return super.update(db);
	}

	/**
	 * 获取待支付订单
	 *
	 * @param start
	 *            开始时间
	 * @param end
	 *            结束时间
	 * @return
	 */
	public List<DepositOrderEntity> findWaitpayOrder(Date start, Date end) {
		Searchable searchable = Searchable.newSearchable();
		searchable.addSearchParam("markDelete_eq", MARK_DELETE_NO);
		searchable.addSearchParam("depositDate_gte", start);
		searchable.addSearchParam("depositDate_lt", end);
		searchable.addSearchParam("status_eq", DepositOrderStatusEnum.WAIT_PAY.getCode());
		searchable.addSearchParam("quickRefueling_eq", QuickRefueling.N);
		searchable.addSearchParam("source_eq", Constants.APP);
		Page<DepositOrderEntity> page = depositOrderRepository.findAll(searchable);
		return page.getContent();
	}


	/**
	 * 保存赠送订单
	 * @param customerSource
	 * @param account
	 * @param money
	 */
	public DepositOrderEntity saveGiftOrder(CustomerSourceBizBean customerSource
			, CustomerHeadBizBean customerHead, CustomerAccountEntity account, Long money,String orderNo,String source) {
		// 记录客户充值
		DepositOrderEntity order = new DepositOrderEntity();
		// 账户ID
		order.setAccountId(account.getAccountId());
		// 充值金额
		order.setAmount(money);
		// 创建时间
		order.setCreatedDate(new Date());
		// 客户ID
		order.setCustomerId(account.getCustomerId());
		// 充值时间
		order.setDepositDate(order.getCreatedDate());
		// 完成时间
		order.setFinishDate(order.getCreatedDate());
		// 已开票金额
		order.setInvoicedAmount(money);
		// 昵称
//		order.setNickname(customerSource.getNickName());
		// 油号
		order.setOilNo(OilNo.PO.getCode());
		// 订单号
		order.setOrderNo(orderNo);
		// 状态
		order.setStatus(DepositOrderStatusEnum.SUCCESS.getCode());
		// 来源
		order.setSource(source);
		// 是否快速加油
		order.setQuickRefueling(QuickRefueling.N);
		// 快速加油订单号
		// order.setRefuelingOrderNo(refuelingOrderNo);
		// 支付方式
		order.setPayMode(PayMode.GIFT.getCode());
		if(customerHead != null){
			// 手机号码
			order.setPhoneNo(customerHead.getPhone());
			// 用户名称
			order.setNickname(customerHead.getNickName());
		}
		// 预购油订单号
		// order.setPrepayNo(generater.newNo(NoType.PAYMENT));
		// 支付单号
		// order.setPayNo(payNo);
		order = save(order);
		return order;
	}
	
	public DepositOrderEntity saveOrder(CustomerSourceBizBean customerSource, CustomerHeadBizBean customerHead, CustomerAccountEntity account, long money
			, String source, PayMode payModel,String orderNo) {
		// 记录客户充值
		DepositOrderEntity order = new DepositOrderEntity();
		// 账户ID
		order.setAccountId(account.getAccountId());
		// 充值金额
		order.setAmount(money);
		// 创建时间
		order.setCreatedDate(new Date());
		// 客户ID
		order.setCustomerId(account.getCustomerId());
		// 充值时间
		order.setDepositDate(order.getCreatedDate());
		// 完成时间
		order.setFinishDate(order.getCreatedDate());
		// 已开票金额
		order.setInvoicedAmount(money);
		// 昵称
//		order.setNickname(customerSource.getNickName());
		// 油号
		order.setOilNo(OilNo.PO.getCode());
		// 订单号
		order.setOrderNo(orderNo);
		// 状态
		order.setStatus(DepositOrderStatusEnum.SUCCESS.getCode());
		// 来源
		order.setSource(source);
		// 是否快速加油
		order.setQuickRefueling(QuickRefueling.N);
		// 快速加油订单号
		// order.setRefuelingOrderNo(refuelingOrderNo);
		// 支付方式
		order.setPayMode(payModel.getCode());
		if(customerHead != null){
			// 手机号码
			order.setPhoneNo(customerHead.getPhone());
			// 用户名称
			order.setNickname(customerHead.getNickName());
		}
		// 预购油订单号
		// order.setPrepayNo(generater.newNo(NoType.PAYMENT));
		// 支付单号
		// order.setPayNo(payNo);
		order = save(order);
		return order;
	}

	/**
	 * 判断用户本月是否赠送过
	 * 
	 * @param customerId
	 * @return	true ：本月未赠送  false：本月已经赠送
	 */
	private boolean isCurMonthFirstChargeBigThanLimit(String customerId) {
		// 本月开始
		Date startDate = DateUtil.getStartDateOfMonth(new Date());
		// 本月结束
		Date endDate = DateUtil.getEndDateOfMonth(new Date());
		DepositOrderEntity order = depositOrderRepository.findCustomerCurMonthGiftCharge(customerId, startDate, endDate);
		return order == null;
	}
	
	public DepositOrderEntity createSinopecGoodDriverPayingOrder(CustomerAccountEntity account, CustomerHeadEntity head, long actAmount,long amount) {
		// 记录客户充值
		DepositOrderEntity order = new DepositOrderEntity();
		// 账户ID
		order.setAccountId(account.getAccountId());
		// 充值金额
		order.setAmount(amount);
		// 实际支付金额
		order.setPayAmount(actAmount);
		// 创建时间
		order.setCreatedDate(new Date());
		// 客户ID
		order.setCustomerId(account.getCustomerId());
		// 充值时间
		order.setDepositDate(order.getCreatedDate());
		// 完成时间
		order.setFinishDate(order.getCreatedDate());
		// 已开票金额
		order.setInvoicedAmount(0l);
		// 油号
		order.setOilNo(OilNo.PO.getCode());
		// 订单号
		order.setOrderNo(generater.newOrderNo());
		// 状态
		order.setStatus(DepositOrderStatusEnum.WAIT_PAY.getCode());
		// 来源
		order.setSource(OrderSourceEnum.PINGANYOUHUI.getCode());
		// 是否快速加油
		order.setQuickRefueling(QuickRefueling.Y);
		// 快速加油订单号
		// order.setRefuelingOrderNo(refuelingOrderNo);
		// 支付方式
//		order.setPayMode(payModel.getCode());
		if(head != null){
			// 手机号码
			order.setPhoneNo(head.getPhone());
			// 用户名称
			order.setNickname(head.getNickName());
		}
		// 预购油订单号
		// order.setPrepayNo(generater.newNo(NoType.PAYMENT));
		// 支付单号
		// order.setPayNo(payNo);
		order = save(order);
		return order;
	}
	

	public Map<String, Object> beforeCreateOrder(String phone, String customerId) {
		Map<String, Object> result = new HashMap<String, Object>();
		String white = customerWhiteService.getMobileWhite(phone);
		// 获取用户可充值限额
		if(white.equals(Constants.YES)){
			PropertyEntity limitProp = propertyService.getPropertyByKey(WHITE_MOBILE_RECHARGE_LIMIT);
			if (limitProp != null && StringUtils.isNotEmpty(limitProp.getPropertyValue())) {
				/* 限制条件情况说明
				 *limitCon[0] 时间限制年月
				 *limitCon[1] 时间数量限制，开始时间到现在的时间单位数量
				 *limitCon[2] 充值金额限制
				 *limitCon[3] 折扣
				 *比如 year_1_400000_0.94 代表1年之内充值金额不大于4000，享受94折优惠
				 *比如 month_3_100000_0.5 代表3个月之内充值金额不大于1000，享受5折优惠
				 */
				String[] limitCon = limitProp.getPropertyValue().split("_");
				Date end = DateUtil.getEndDateOfMonth(new Date());
				Date start = null;
				if (Constants.YEAR.equals(limitCon[0])) {
					start = DateUtil.changeYear(end, -1 * Integer.parseInt(limitCon[1]));
				} else if (Constants.MONTH.equals(limitCon[0])) {
					start = DateUtil.changeMonth(end, -1 * (Integer.parseInt(limitCon[1]) - 1));
				} else {
					// 不限制
					start = DateUtil.changeYear(end, -100);
				}
				start = DateUtil.getStartDateOfMonth(start);
				// 统计已经充值金额
				Double sumRechargeValue = depositOrderRepository.sumRechargeByUserIdAndBetweenDate(customerId, start, end);
				if(sumRechargeValue == null){
					sumRechargeValue = 0.0;
				}
				result.put("rest", (Double.parseDouble(limitCon[2]) - sumRechargeValue > 0 ? (Double.parseDouble(limitCon[2]) - sumRechargeValue) / 100 : 0.0));
				result.put("discount", limitCon[3]);
			}
		}
		result.put("enjoy", white);
		return result;
	}

	private void checkWihteChargeAmount(DepositOrderEntity order, CustomerHeadBizBean customer) {
		Map<String, Object> result = beforeCreateOrder(customer.getPhone(), customer.getEntityId());
		String enjoy = result.get("enjoy").toString();
		if (enjoy.equals(Constants.YES)) {
			BigDecimal rest = new BigDecimal(result.get("rest").toString()).multiply(new BigDecimal(100));
			BigDecimal discount =  new BigDecimal(result.get("discount").toString());
			BigDecimal payAmount = BigDecimal.ZERO;
			if(order.getAmount() > rest.longValue()){
				payAmount = new BigDecimal(order.getAmount()).subtract(rest).add(rest.multiply(discount));
			} else {
				payAmount = new BigDecimal(order.getAmount()).multiply(discount);
			}
			// 四舍五入
			payAmount = payAmount.setScale(0, RoundingMode.HALF_UP);
			order.setPayAmount(payAmount.longValue());
			log.info("500测试用户:[{}] 具有加油折扣：[{}] 实际支付:[{}]分 实际到账金额:[{}]分，目前已经剩余:[{}]分可以享受优惠! 计算出来的应支付金额为：[{}]"
					,customer.getPhone(),discount.toString(),order.getPayAmount(),order.getAmount(),rest.toString(),payAmount.longValue());
//			if(payAmount.longValue() != order.getPayAmount()){
//				throw new BusinessException("1020", "您实际支付的金额和订单应付的金额不匹配!");
//			}
		}
	}

	public List<DepositOrderEntity> findByCustomerIdAndRefuelingOrderNo(String customerId, List<String> orderNos) {
		return depositOrderRepository.findByCustomerIdAndRefuelingOrderNo(customerId,orderNos);
	}
	
}
